package com.example.pwj.ffstudy.ui.zhihu.view;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.example.pwj.ffstudy.R;
import com.example.pwj.ffstudy.bean.zdaily.ZDailyExtra;
import com.example.pwj.ffstudy.bean.zdaily.ZDailyStoryDetail;
import com.example.pwj.ffstudy.ui.fragment.ContainerFragment;
import com.example.pwj.ffstudy.ui.fragment.FmManager;
import com.example.pwj.ffstudy.ui.zhihu.ZhiConst;
import com.example.pwj.ffstudy.ui.zhihu.contract.ZNewsDetailContract;
import com.example.pwj.ffstudy.ui.zhihu.di.DaggerZNewsPComponent;
import com.example.pwj.ffstudy.ui.zhihu.presenter.ZNewsDetailPresenter;
import com.example.pwj.ffstudy.util.HtmlUtils;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * Created by pwj on 2017/8/25.
 */

public class ZNewsDetailFragment extends ContainerFragment implements ZNewsDetailContract.View, View.OnClickListener {
    @BindView(R.id.loadingLayout)
    FrameLayout mLoadingLayout;
    @BindView(R.id.container)
    FrameLayout mContainer;
    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;
    private WebView mWebView;
    @Inject
    ZNewsDetailPresenter mPresenter;
    private TextView tv_pop;
    private TextView tv_comment;
    private int story_id;
    private ZDailyExtra zDailyExtra;

    @Override
    protected void initFm() {
        initView();
        initData();
    }

    private void initData() {
        DaggerZNewsPComponent.builder()
                .build()
                .inject(this);
        mPresenter.takeView(this);
        Bundle arguments = getArguments();
        story_id = arguments.getInt(ZhiConst.ZHIHU_ID, 0);
        mPresenter.loadZDailyStoryDetail(story_id);
    }

    private void initView() {
        mActionBar.setDisplayShowTitleEnabled(false);
        mWebView = (WebView) View.inflate(mContext.getApplicationContext(), R.layout.layout_webview, null);
        mContainer.addView(mWebView);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDomStorageEnabled(true);
        getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
        mWebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
        mWebView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        mWebView.setWebChromeClient(new ChromeClient());
        mWebView.setWebViewClient(new NewsWebViewClient());
        mWebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
                        mWebView.goBack();
                        return true;
                    }
                }
                return false;
            }
        });
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.newsdetail_menu, menu);
        tv_pop = (TextView) menu.findItem(R.id.item_pop).getActionView();
        tv_comment = (TextView) menu.findItem(R.id.item_comment).getActionView();
        tv_pop.setOnClickListener(this);
        tv_comment.setOnClickListener(this);
        mPresenter.loadZDailyExtra(story_id);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                    return true;
                } else {
                    return super.onOptionsItemSelected(item);
                }
        }
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_comment:
                Bundle bundle = new Bundle();
                bundle.putInt(ZhiConst.ZHIHU_ID,story_id);
                bundle.putParcelable(ZhiConst.ZDAILY_EXTRA,zDailyExtra);
                FmManager.startAct(ZNewsDetailFragment.this,ZNewsCommFragment.class.getName(),bundle);
                break;
        }
    }

    //web视图
    private class NewsWebViewClient extends WebViewClient {
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            view.loadUrl(url);
            startAct(url);
            return true;
        }
    }

    public void startAct(String url) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        startActivity(intent);
    }

    private class ChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            mProgressBar.setProgress(newProgress);
            if (newProgress == 100) {
                mLoadingLayout.setVisibility(View.GONE);
            } else {
                mLoadingLayout.setVisibility(View.VISIBLE);
            }
        }


        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_znewsdetail;
    }

    @Override
    public void onLoadZDailyDetail(ZDailyStoryDetail zDailyStoryDetail) {
        String html = HtmlUtils.createHtmlData(zDailyStoryDetail);
        mWebView.loadData(html, HtmlUtils.MIME_TYPE, HtmlUtils.ENCODING);
    }

    @Override
    public void onLoadZDailyExtra(ZDailyExtra zDailyExtra) {
        this.zDailyExtra = zDailyExtra;
        tv_pop.setText(String.valueOf(zDailyExtra.getPopularity()));
        tv_comment.setText(String.valueOf(zDailyExtra.getComments()));
    }

    @Override
    public void onError() {

    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onDestroyView() {
        if (mWebView != null) {
            mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWebView.clearHistory();
            mContainer.removeView(mWebView);
            mWebView.destroy();
            mWebView = null;
        }
        if (mPresenter != null) {
            mPresenter.dropView();
            mPresenter = null;
        }
        super.onDestroyView();
    }
}
